<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>修改密码</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <style>
        .password-container {
            padding: 20px;
        }

        .password-form {
            max-width: 400px;
            margin: 0 auto;
        }

        .password-rules {
            background: #f8f8f8;
            border-left: 4px solid #1E9FFF;
            padding: 10px 15px;
            margin: 15px 0;
            border-radius: 2px;
        }

        .password-rules h4 {
            margin: 0 0 8px 0;
            color: #333;
            font-size: 14px;
        }

        .password-rules ul {
            margin: 0;
            padding-left: 20px;
            color: #666;
        }

        .password-rules li {
            margin-bottom: 4px;
            font-size: 12px;
        }

        .form-footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .strength-meter {
            height: 4px;
            background: #f0f0f0;
            border-radius: 2px;
            margin-top: 5px;
            overflow: hidden;
        }

        .strength-level {
            height: 100%;
            width: 0;
            transition: all 0.3s;
        }

        .strength-weak {
            background: #FF5722;
            width: 33%;
        }

        .strength-medium {
            background: #FFB800;
            width: 66%;
        }

        .strength-strong {
            background: #5FB878;
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="password-container">
        <form class="layui-form password-form" lay-filter="passwordForm">
            <input type="hidden" id="userId" name="user_id">

            <!-- 当前用户信息展示 -->
            <div class="layui-form-item">
                <label class="layui-form-label">当前用户</label>
                <div class="layui-input-block">
                    <div class="layui-form-mid" id="currentUserInfo">
                        <i class="layui-icon layui-icon-username"></i>
                        <span id="userNameDisplay"></span>
                        (<span id="userIdDisplay"></span>)
                    </div>
                </div>
            </div>

            <!-- 原密码 -->
            <div class="layui-form-item">
                <label class="layui-form-label">原密码</label>
                <div class="layui-input-block">
                    <input type="password" name="old_password" lay-verify="required" placeholder="请输入当前密码"
                        autocomplete="off" class="layui-input">
                </div>
            </div>

            <!-- 新密码 -->
            <div class="layui-form-item">
                <label class="layui-form-label">新密码</label>
                <div class="layui-input-block">
                    <input type="password" name="new_password" id="newPassword" lay-verify="required|pass"
                        placeholder="请输入新密码" autocomplete="new-password" class="layui-input">
                    <div class="strength-meter">
                        <div class="strength-level" id="passwordStrength"></div>
                    </div>
                </div>
            </div>

            <!-- 确认密码 -->
            <div class="layui-form-item">
                <label class="layui-form-label">确认密码</label>
                <div class="layui-input-block">
                    <input type="password" name="confirm_password" lay-verify="required|confirmPass"
                        placeholder="请再次输入新密码" autocomplete="new-password" class="layui-input">
                </div>
            </div>

            <!-- 密码规则提示 -->
            <div class="password-rules">
                <h4>密码安全要求：</h4>
                <ul>
                    <li>长度至少8个字符</li>
                    <li>包含字母和数字</li>
                    <li>可包含特殊字符 @$!%*?&</li>
                    <li>不能与旧密码相同</li>
                </ul>
            </div>

            <div class="form-footer">
                <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="passwordSubmit">
                    <i class="layui-icon layui-icon-ok"></i> 确认修改
                </button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closePopup()">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </form>
    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;

            let currentUserId = '';
            let currentUserName = '';

            // 页面初始化
            initPage();

            // 密码强度检测
            $('#newPassword').on('input', function () {
                checkPasswordStrength(this.value);
            });

            // 表单验证规则
            form.verify({
                pass: function (value) {
                    if (value.length < 8) {
                        return '密码长度至少8个字符';
                    }
                    if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
                        return '密码必须包含字母和数字';
                    }
                },
                confirmPass: function (value) {
                    var newPassword = $('input[name="new_password"]').val();
                    if (value !== newPassword) {
                        return '两次输入的密码不一致';
                    }
                }
            });

            // 表单提交
            form.on('submit(passwordSubmit)', function (data) {
                submitPasswordChange(data.field);
                return false;
            });

            function initPage() {
                // 获取URL参数
                const urlParams = new URLSearchParams(window.location.search);
                const userId = urlParams.get('user_id');

                if (userId) {
                    currentUserId = userId;
                    // 加载用户信息
                    loadUserInfo(userId);
                } else {
                    // 如果没有指定用户，使用当前登录用户
                    loadCurrentUser();
                }
            }

            function loadUserInfo(userId) {
                http.get(API_CONFIG.ADMIN.USERS + '/' + userId)
                    .then(function (res) {
                        if (res.data) {
                            currentUserName = res.data.user_name;
                            $('#userId').val(res.data.user_id);
                            $('#userNameDisplay').text(res.data.user_name);
                            $('#userIdDisplay').text(res.data.user_id);
                        }
                    })
                    .catch(function (error) {
                        console.error('加载用户信息失败:', error);
                        layer.msg('加载用户信息失败', { icon: 2 });
                    });
            }

            function loadCurrentUser() {
                // 从本地存储获取当前用户信息
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    try {
                        const user = JSON.parse(userStr);
                        currentUserId = user.user_id;
                        currentUserName = user.user_name;
                        $('#userId').val(user.user_id);
                        $('#userNameDisplay').text(user.user_name);
                        $('#userIdDisplay').text(user.user_id);
                    } catch (e) {
                        console.error('解析用户信息失败:', e);
                    }
                }
            }

            function checkPasswordStrength(password) {
                var strengthBar = $('#passwordStrength');
                var strength = 0;

                if (password.length >= 8) strength++;
                if (/[a-z]/.test(password)) strength++;
                if (/[A-Z]/.test(password)) strength++;
                if (/\d/.test(password)) strength++;
                if (/[@$!%*?&]/.test(password)) strength++;

                strengthBar.removeClass('strength-weak strength-medium strength-strong');

                if (strength <= 2) {
                    strengthBar.addClass('strength-weak');
                } else if (strength <= 4) {
                    strengthBar.addClass('strength-medium');
                } else {
                    strengthBar.addClass('strength-strong');
                }
            }

            function submitPasswordChange(formData) {
                var loadingIndex = layer.load(1);

                const submitData = {
                    user_id: formData.user_id || currentUserId,
                    old_password: formData.old_password,
                    new_password: formData.new_password
                };

                http.post(API_CONFIG.ENDPOINTS.CHANGE_PASSWORD, submitData)
                    .then(function (response) {
                        layer.close(loadingIndex);
                        layer.msg('密码修改成功', {
                            icon: 1,
                            time: 1500,
                            end: function () {
                                // 通知父窗口操作完成
                                if (window.parent) {
                                    window.parent.postMessage({
                                        type: 'passwordChanged',
                                        success: true,
                                        user_id: currentUserId
                                    }, '*');
                                }
                                closePopup();
                            }
                        });
                    })
                    .catch(function (error) {
                        layer.close(loadingIndex);
                        console.error('修改密码失败:', error);
                        layer.msg('修改密码失败: ' + (error.msg || error.message), { icon: 2, time: 3000 });
                    });
            }
        });

        // 关闭弹窗
        function closePopup() {
            if (window.parent && window.parent.layer) {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            }
        }

        // 供父窗口调用的函数
        window.setUserInfo = function (userId, userName) {
            $('#userId').val(userId);
            $('#userNameDisplay').text(userName);
            $('#userIdDisplay').text(userId);
        };
    </script>
</body>

</html>